import { useEffect } from "react";
import { Pagination, Table, Space, Popconfirm, Divider, message } from "antd";
import { Card as SemiCard, ButtonGroup, Button } from "@douyinfe/semi-ui";
import { IconRefresh, IconPlusCircle } from "@douyinfe/semi-icons";
import { useModel } from "umi";
import { useReactive } from "ahooks";

import { FindAllIndustryType } from "../../_graphql/resources";

import AddIndustryType from "../../_modals/industry_type/add";
import EditIndustryType from "../../_modals/industry_type/edit";

const { Column } = Table;

const IndustryType = () => {
    const { windowInnerHeight, graphqlFetchPlatform } = useModel("global");
    const { setModalVisible, setModalTitle, setModalWidth, setModalComponent } = useModel("global.modal");

    const state = useReactive({
        loading: false,
        submitLoading: false,
        industryTypes: [],
        pageSize: 25,
        page: 1,
        totalCount: 0,
    });

    const loadData = async () => {
        state.loading = true;
        let res = await graphqlFetchPlatform({ query: FindAllIndustryType, variables: { first: state.pageSize, offset: (state.page - 1) * state.pageSize || 0 } });
        state.industryTypes = res?.a?.nodes || [];
        state.totalCount = res?.a?.totalCount || 0;
        state.loading = false;
    };

    useEffect(() => {
        loadData();
    }, [state.page]);

    const openAddModal = () => {
        setModalTitle("添加信息");
        setModalWidth(600);
        setModalComponent(<AddIndustryType industryTypes={state.industryTypes} reloadData={loadData} />);
        setModalVisible(true);
    };

    const openEditModal = (record) => {
        setModalTitle("编辑信息");
        setModalWidth(600);
        setModalComponent(<EditIndustryType record={record} industryTypes={state.industryTypes} reloadData={loadData} />);
        setModalVisible(true);
    };

    const deleteItem = async (item) => {
        state.submitLoading = true;
        let res = await graphqlFetchPlatform({
            query: `query MyQuery($industryType: String!) { a: allOrganizationBaseInformations( condition: { industryType: $industryType } ) { totalCount } }`,
            variables: { industryType: item.itName },
        });
        if (res) {
            if (res.a?.totalCount === 0) {
                res = await graphqlFetchPlatform({
                    query: `mutation MyMutation($itUuid: UUID!) { deleteIndustryTypeByItUuid(input: { itUuid: $itUuid }) { clientMutationId } }`,
                    variables: { itUuid: item.itUuid },
                });
                if (res) {
                    message.success("成功删除信息");
                    loadData();
                }
            } else {
                message.warning("该信息已被使用, 不能删除");
            }
        }
        state.submitLoading = false;
    };

    // 窗口头部：30，应用头：60，操作区内边距：24，卡面头：54，修正值：4
    const cardBodyHeight = windowInnerHeight - 90 - 20 - 54 - 60;

    return (
        <div style={{ padding: 10 }}>
            <SemiCard
                title={<span style={{ lineHeight: "32px", fontSize: 16, fontWeight: 600 }}>组织行业类型信息</span>}
                headerExtraContent={
                    <ButtonGroup>
                        <Button icon={<IconPlusCircle />} onClick={openAddModal}>
                            添加行业类型
                        </Button>
                        <Button icon={<IconRefresh />} onClick={loadData}>
                            重新加载
                        </Button>
                    </ButtonGroup>
                }
                headerStyle={{ padding: "10px 14px" }}
                shadows="always"
                bordered={false}
                bodyStyle={{ padding: 0, height: cardBodyHeight }}
                footerStyle={{ padding: 0 }}
                footerLine={true}
                footer={
                    <div style={{ padding: 14, display: "flex", justifyContent: "space-between" }}>
                        <div></div>
                        <Pagination
                            total={state.totalCount}
                            pageSize={state.pageSize}
                            position={["none", "bottomCenter"]}
                            hideOnSinglePage={false}
                            showSizeChanger={false}
                            showTotal={(total) => `总共：${total}条`}
                            onChange={(page) => (state.page = page)}
                        />
                    </div>
                }
            >
                <Table loading={state.loading} dataSource={state.industryTypes} bordered pagination={false} rowKey="itUuid" scroll={{ y: cardBodyHeight - 55 }}>
                    <Column title="UUID" dataIndex="itUuid" align="center" width={320} />
                    <Column title="行业类型名称" dataIndex="itName" align="left" />
                    <Column title="参考数据库" dataIndex="itRedb" align="left" />
                    <Column title="GraphQL服务名称" dataIndex="itDbna" align="left" width={180} />
                    <Column title="领域类型" dataIndex="itType" align="left" width={160} />
                    <Column
                        title="操作"
                        align="center"
                        width={160}
                        render={(_, r) => {
                            return (
                                <Space split={<Divider type="vertical" />}>
                                    <a onClick={() => openEditModal(r)}>编辑</a>
                                    <Popconfirm title="确认要删除该信息吗?" okButtonProps={{ loading: state.submitLoading }} placement="topRight" onConfirm={() => deleteItem(r)}>
                                        <a>删除</a>
                                    </Popconfirm>
                                </Space>
                            );
                        }}
                    />
                </Table>
            </SemiCard>
        </div>
    );
};

export default IndustryType;
